<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if (!defined('BLOCK_SIZE')) define('BLOCK_SIZE', 32);

if (!defined('CIPHER_KEY')) define('CIPHER_KEY', 'bG9uZ2hvYW5nZ2lhbmc=');

class AESCipher {
	
	private $iv = 'z4mP372E3t17686W';
	private $key;
	
	public function __construct() {
		$this->key = $this->get_key();
	}
	
	function test() {
		$key = base64_decode(CIPHER_KEY);
		return $key;
	}
	
	private function get_key() {
		return $this->pkcs5pad(base64_decode(CIPHER_KEY));
	} 
	
	public function encrypt($plain_text) {
		$iv = $this->iv;
		$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
		mcrypt_generic_init($td, $this->key, $iv);
		$encrypted = mcrypt_generic($td, $this->pkcs5pad($plain_text));
		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);
// 		$result = bin2hex($iv . $encrypted);		// use base64_decode instead of bin2hex
		$result = base64_encode($iv . $encrypted);	
		return $result;
	}
	
	public function decrypt($cipher_text) {
		if ($cipher_text == '' || $cipher_text == null) 
			return '';
// 		$cipher_text = $this->hex2bin($cipher_text);		// use base64_decode instead of hex2bin
		$cipher_text = base64_decode($cipher_text);
		$iv = substr($cipher_text, 0, 16);
		$content = substr($cipher_text, 16, strlen($cipher_text) - 1);
		$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
		mcrypt_generic_init($td, $this->key, $iv);
		$decrypted = mdecrypt_generic($td, $content);
		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);
		$out = $this->pkcs5unpad(trim($decrypted));
		return $out;
	}
	
	private function bin2hex($str) {
		return bin2hex($str);
	}
	
	private function hex2bin($hex) {
		$bin = '';
		for ($i=0;$i<strlen($hex);$i+=2) {
			$bin .= chr(hexdec(substr($hex, $i, 2)));
		}
		return $bin;
	}
	
	private function pkcs5pad($str) {
		$pad = BLOCK_SIZE - (strlen($str) % BLOCK_SIZE);
		return $str . str_repeat(chr($pad), $pad);
	}
	
	private function pkcs5unpad($str) {
		$pad = ord($str[strlen($str) - 1]);
		if ($pad > strlen($str)) {
			return false;
		}
		if (strspn($str, chr($pad), strlen($str) - $pad) != $pad) 
			return false;
		return substr($str, 0, -1 * $pad);
	}
}